<template>
  <div class="consumption-stats-container">
    <n-h3 style="margin: 0 0 16px 0;">🍽️ 餐厅消费统计分析</n-h3>
    
    <n-radio-group v-model:value="activeTab" name="tabGroup" style="margin-bottom: 20px;">
      <n-radio-button 
        v-for="tab in tabs" 
        :key="tab.value" 
        :value="tab.value"
        :label="tab.label"
      />
    </n-radio-group>
    
    <n-radio-group v-model:value="chartType" name="chartType" style="margin-bottom: 20px;">
      <n-radio-button 
        v-for="type in chartTypes" 
        :key="type.value" 
        :value="type.value"
        :label="type.label"
      />
    </n-radio-group>
    
    <div v-if="loading" style="text-align: center; padding: 50px;">
      <n-spin size="large" />
      <div style="margin-top: 10px; color: #666;">数据加载中...</div>
    </div>
    
    <div v-else class="chart-wrapper">
      <v-chart 
        :option="chartOption" 
        autoresize 
        style="background-color: #ffffff; height: 500px; border-radius: 8px;"
      />
    </div>
    
    <div class="table-area">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :bordered="true"
        style="margin-top: 20px;"
      />
      
      <div class="pagination-wrapper">
        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          :page-size="pagination.pageSize"
          @update:page="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  NH3,
  NRadioGroup,
  NRadioButton,
  NDataTable,
  NPagination,
  NSpin
} from 'naive-ui'
import { use } from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import convertProvince from "@/tools/convertProvince"

import {
  getGradeConsumptionTrend,
  getGradeConsumptionTrendByMonth,
  getGradeConsumptionSummary,
  getGenderConsumptionSummary,
  getLocationConsumptionSummary
} from "@/api/consumptionTrend"

use([
  BarChart,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent,
  CanvasRenderer
])

// 选项卡配置
const tabs = ref([
  { label: '年级消费趋势', value: 'gradeTrend' },
  { label: '年级消费总计', value: 'gradeTotal' },
  { label: '性别消费总计', value: 'genderTotal' },
  { label: '省份消费总计', value: 'provinceTotal' }
])

const activeTab = ref('gradeTrend')

// 图表类型配置
const chartTypes = ref([
  { label: '柱状图', value: 'bar' },
  { label: '折线图', value: 'line' },
  { label: '堆积图', value: 'stack' }
])

const chartType = ref('bar')

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 5,
  pageCount: 1
})

const handlePageChange = (page) => {
  pagination.value.page = page
}

// 数据加载状态
const loading = ref(false)

// 日期范围
const dateRange = ref({
  startDate: '',
  endDate: ''
})

// API调用函数
const fetchData = async () => {
  loading.value = true
  try {
    let response
    switch (activeTab.value) {
      case 'gradeTrend':
        // 分别获取12个月的数据
        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        const grades = ['1级', '2级', '3级', '4级']
        const currentYear = new Date().getFullYear()
        
        // 初始化数据结构
        const trendData = months.map(month => {
          const monthData = { month }
          grades.forEach(grade => {
            monthData[grade] = 0
          })
          return monthData
        })
        
        // 获取每个月的数据
        for (let i = 0; i < 12; i++) {
          const month = i + 1
          const monthResponse = await getGradeConsumptionTrendByMonth(currentYear, month)
          const monthData = monthResponse.data.data || []
          
          // 将当月数据填充到对应月份
          monthData.forEach(item => {
            const grade = `${item.grade}级`
            if (trendData[i] && trendData[i][grade] !== undefined) {
              trendData[i][grade] = item.totalAmount || 0
            }
          })
        }
        
        rawData.value.gradeTrend = trendData
        break
        
      case 'gradeTotal':
        response = await getGradeConsumptionSummary(dateRange.value.startDate, dateRange.value.endDate)
        // 处理年级消费总计数据
        rawData.value.gradeTotal = response.data.data.map(item => ({
          grade: `${item.grade}级`,
          total: item.totalAmount
        }))
        break
        
      case 'genderTotal':
        response = await getGenderConsumptionSummary(dateRange.value.startDate, dateRange.value.endDate)
        // 处理性别消费总计数据
        rawData.value.genderTotal = response.data.data.map(item => ({
          gender: item.gender,
          total: item.totalAmount
        }))
        break
        
      case 'provinceTotal':
        response = await getLocationConsumptionSummary(dateRange.value.startDate, dateRange.value.endDate, 'province')
        // 处理省份消费总计数据
        rawData.value.provinceTotal = response.data.data.map(item => ({
          province: convertProvince(item.province),
          total: item.totalAmount
        }))
        break
        
      default:
        response = await getGradeConsumptionTrend(dateRange.value.startDate, dateRange.value.endDate)
        rawData.value.gradeTrend = response.data.data || []
    }
    
    // 更新分页
    pagination.value.pageCount = Math.ceil(rawData.value[activeTab.value].length / pagination.value.pageSize)
    if (pagination.value.page > pagination.value.pageCount) {
      pagination.value.page = 1
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    // 可以在这里添加错误提示
  } finally {
    loading.value = false
  }
}

// 监听选项卡变化，重新获取数据
watch(activeTab, () => {
  fetchData()
})

// 初始化数据
onMounted(() => {
  fetchData()
})

// 山东农业大学餐厅消费模拟数据（作为备用数据）
const rawData = ref({
  // 各月份各年级消费趋势
  gradeTrend: [
    { month: '1月', '1级': 12560, '2级': 11890, '3级': 10500, '4级': 9800 },
    { month: '2月', '1级': 13200, '2级': 12450, '3级': 11000, '4级': 9200 },
    { month: '3月', '1级': 14200, '2级': 13500, '3级': 11500, '4级': 9500 },
    { month: '4月', '1级': 13800, '2级': 12800, '3级': 12000, '4级': 10000 },
    { month: '5月', '1级': 14500, '2级': 13200, '3级': 12500, '4级': 10500 },
    { month: '6月', '1级': 12800, '2级': 11800, '3级': 11000, '4级': 9800 },
    { month: '7月', '1级': 11500, '2级': 10500, '3级': 9500, '4级': 8500 },
    { month: '8月', '1级': 9800, '2级': 9200, '3级': 8800, '4级': 8000 },
    { month: '9月', '1级': 15200, '2级': 14200, '3级': 13500, '4级': 12500 },
    { month: '10月', '1级': 14800, '2级': 13800, '3级': 12800, '4级': 11800 },
    { month: '11月', '1级': 14200, '2级': 13200, '3级': 12200, '4级': 11200 },
    { month: '12月', '1级': 13500, '2级': 12500, '3级': 11500, '4级': 10500 }
  ],
  // 各年级年度消费总计
  gradeTotal: [
    { grade: '1级', total: 158000 },
    { grade: '2级', total: 145000 },
    { grade: '3级', total: 132000 },
    { grade: '4级', total: 120000 }
  ],
  // 性别消费总计
  genderTotal: [
    { gender: '男生', total: 285000 },
    { gender: '女生', total: 270000 }
  ],
  // 省份消费总计
  provinceTotal: [
    { province: '山东省', total: 185000 },
    { province: '河南省', total: 58000 },
    { province: '河北省', total: 42000 },
    { province: '江苏省', total: 38000 },
    { province: '安徽省', total: 35000 },
    { province: '山西省', total: 28000 },
    { province: '陕西省', total: 25000 },
    { province: '四川省', total: 22000 }
  ]
})

// 表格配置
const columns = computed(() => {
  if (activeTab.value === 'gradeTrend') {
    return [
      { title: '月份', key: 'month', width: 100 },
      { title: '1级', key: '1级', width: 100 },
      { title: '2级', key: '2级', width: 100 },
      { title: '3级', key: '3级', width: 100 },
      { title: '4级', key: '4级', width: 100 }
    ]
  } else {
    return [
      { title: activeTab.value === 'provinceTotal' ? '省份' : 
                activeTab.value === 'genderTotal' ? '性别' : '年级', 
        key: 'name', width: 120, ellipsis: { tooltip: true } },
      { title: '消费总额(元)', key: 'total', width: 120 },
      { 
        title: '占比', 
        key: 'percentage',
        width: 100,
        render: (row) => `${row.percentage}%`
      }
    ]
  }
})

// 计算表格数据
const tableData = computed(() => {
  let data = rawData.value[activeTab.value]
  
  if (activeTab.value !== 'gradeTrend') {
    const total = data.reduce((sum, cur) => sum + cur.total, 0) || 1
    data = data.map(item => ({
      name: item.grade || item.gender || item.province,
      total: item.total,
      percentage: ((item.total / total) * 100).toFixed(1)
    }))
  }
  
  pagination.value.pageCount = Math.ceil(data.length / pagination.value.pageSize)
  
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return data.slice(start, end)
})

// 图表配置
const chartOption = computed(() => {
  const currentData = rawData.value[activeTab.value]
  const title = `${tabs.value.find(t => t.value === activeTab.value).label} - ${chartTypes.value.find(t => t.value === chartType.value).label}`
  
  if (activeTab.value === 'gradeTrend') {
    return getTrendChartOption(currentData, title)
  } else {
    return getTotalChartOption(currentData, title)
  }
})

// 响应式图表配置
const isMobile = ref(window.innerWidth < 768)

const getBaseOption = (data, title) => {
  const itemCount = data.length
  const defaultShow = isMobile.value ? Math.min(5, itemCount) : Math.min(8, itemCount)
  const startValue = 0
  const endValue = defaultShow - 1
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: isMobile.value ? 14 : 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      confine: true
    },
    grid: {
      left: isMobile.value ? '5%' : '5%',
      right: '5%',
      bottom: isMobile.value ? '15%' : '15%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        bottom: isMobile.value ? '5%' : '5%',
        height: 20,
        startValue,
        endValue,
        handleSize: 12,
        brushSelect: false,
        zoomLock: false,
        filterMode: 'filter',
        moveOnMouseMove: false,
        moveRate: 0.2,
        preventDefaultMouseMove: true
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        startValue,
        endValue,
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
        preventDefaultMouseMove: true
      }
    ]
  }
}

function getTrendChartOption(data, title) {
  const baseOption = getBaseOption(data, title)
  const grades = ['1级', '2级', '3级', '4级']
  
  return {
    ...baseOption,
    legend: {
      data: grades,
      top: 30,
      itemWidth: isMobile.value ? 12 : 16,
      itemHeight: isMobile.value ? 12 : 16,
      textStyle: {
        fontSize: isMobile.value ? 12 : 14
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.month),
      axisLabel: {
        interval: 0,
        fontSize: isMobile.value ? 10 : 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: isMobile.value ? 10 : 12
      },
      name: '消费金额(元)',
      nameTextStyle: {
        fontSize: isMobile.value ? 10 : 12
      }
    },
    series: grades.map((grade, index) => ({
      name: grade,
      type: chartType.value === 'line' ? 'line' : 'bar',
      barWidth: isMobile.value ? 12 : 20,
      stack: chartType.value === 'stack' ? 'total' : null,
      data: data.map(item => item[grade]),
      itemStyle: {
        color: ['#5B8FF9', '#61DDAA', '#F6BD16', '#7262FD'][index % 4]
      },
      ...(chartType.value === 'line' ? {
        symbol: 'circle',
        symbolSize: isMobile.value ? 6 : 8,
        lineStyle: {
          width: isMobile.value ? 2 : 3
        }
      } : {})
    }))
  }
}

function getTotalChartOption(data, title) {
  const baseOption = getBaseOption(data, title)
  const nameKey = activeTab.value === 'provinceTotal' ? 'province' : 
                 activeTab.value === 'genderTotal' ? 'gender' : 'grade'
  
  const seriesData = data.map(item => ({
    name: item[nameKey],
    value: item.total
  }))
  
  const total = seriesData.reduce((sum, cur) => sum + cur.value, 0)
  
  if (chartType.value === 'stack') {
    return {
      ...baseOption,
      legend: {
        data: seriesData.map(item => item.name),
        top: 30,
        itemWidth: isMobile.value ? 12 : 16,
        itemHeight: isMobile.value ? 12 : 16,
        textStyle: {
          fontSize: isMobile.value ? 12 : 14
        }
      },
      xAxis: {
        type: 'category',
        data: seriesData.map(item => item.name),
        axisLabel: {
          interval: 0,
          fontSize: isMobile.value ? 10 : 12,
          formatter: function(value) {
            return isMobile.value ? (value.length > 4 ? value.substring(0, 4) + '...' : value) : value
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          fontSize: isMobile.value ? 10 : 12
        },
        name: '消费金额(元)',
        nameTextStyle: {
          fontSize: isMobile.value ? 10 : 12
        }
      },
      series: [{
        name: '消费金额',
        type: 'bar',
        barWidth: isMobile.value ? 12 : 20,
        stack: 'total',
        data: seriesData,
        itemStyle: {
          color: (params) => ['#5B8FF9', '#61DDAA', '#F6BD16', '#7262FD', '#78D3F8'][params.dataIndex % 5]
        },
        label: {
          show: true,
          position: 'top',
          formatter: (params) => `${params.value}\n(${((params.value / total) * 100).toFixed(1)}%)`,
          fontSize: isMobile.value ? 10 : 12
        }
      }]
    }
  }
  
  return {
    ...baseOption,
    xAxis: {
      type: 'category',
      data: seriesData.map(item => item.name),
      axisLabel: {
        interval: 0,
        fontSize: isMobile.value ? 10 : 12,
        formatter: function(value) {
          return isMobile.value ? (value.length > 4 ? value.substring(0, 4) + '...' : value) : value
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: isMobile.value ? 10 : 12
      },
      name: '消费金额(元)',
      nameTextStyle: {
        fontSize: isMobile.value ? 10 : 12
      }
    },
    series: [{
      name: '消费金额',
      type: chartType.value === 'line' ? 'line' : 'bar',
      barWidth: isMobile.value ? 12 : 20,
      data: seriesData,
      itemStyle: {
        color: (params) => ['#5B8FF9', '#61DDAA', '#F6BD16', '#7262FD', '#78D3F8'][params.dataIndex % 5]
      },
      ...(chartType.value === 'line' ? {
        symbol: 'circle',
        symbolSize: isMobile.value ? 6 : 8,
        lineStyle: {
          width: isMobile.value ? 2 : 3
        }
      } : {
        label: {
          show: true,
          position: 'top',
          formatter: (params) => `${params.value}\n(${((params.value / total) * 100).toFixed(1)}%)`,
          fontSize: isMobile.value ? 10 : 12
        }
      })
    }]
  }
}

// 响应式处理
onMounted(() => {
  const updateIsMobile = () => {
    isMobile.value = window.innerWidth < 768
  }
  window.addEventListener('resize', updateIsMobile)
  updateIsMobile()
})
</script>

<style scoped>
.consumption-stats-container {
  padding: 16px;
  background-color: #f7f8fa;
  border-radius: 8px;
  max-width: 100%;
  overflow-x: hidden;
}

.n-radio-group {
  margin-right: 12px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.chart-wrapper {
  width: 100%;
  margin: 0 auto;
  margin-bottom: 30px;
}

.table-area {
  width: 100%;
  margin-top: 20px;
  overflow-x: auto;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 12px 0;
}

:deep(.n-data-table) {
  border-bottom: none;
  margin-bottom: 0;
  min-width: 100%;
}

:deep(.echarts) {
  padding-bottom: 20px;
}

:deep(.echarts-slider) {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .consumption-stats-container {
    padding: 12px;
  }
  
  .chart-wrapper {
    margin-bottom: 0px;
  }
  
  .pagination-wrapper {
    margin-top: 15px;
    padding: 8px 0;
  }
  
  :deep(.n-radio-button) {
    padding: 0 8px;
    font-size: 12px;
  }
  
  :deep(.n-data-table th),
  :deep(.n-data-table td) {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  :deep(.echarts-slider-handle) {
    width: 16px !important;
    height: 20px !important;
  }
}
</style>